<?php
// 应用公共文件
use app\common\service\FileService;
use think\helper\Str;

//数组筛选字段
function array_pick($array, $keys):array
{
    if (empty($array)) {
        return [];
    }

    $result = [];
    foreach ($keys as $key) {
        if (array_key_exists($key, $array)) {
            $result[$key] = $array[$key];
        }
    }

    return $result;
}
/**
 * @notes 生成密码加密密钥
 * @param string $plaintext
 * @param string $salt
 * @return string
 * @author 段誉
 * @date 2021/12/28 18:24
 */
function create_password(string $plaintext, string $salt) : string
{
    return md5($salt . md5($plaintext . $salt));
}


/**
 * @notes 随机生成token值
 * @param string $extra
 * @return string
 * @author 段誉
 * @date 2021/12/28 18:24
 */
function create_token(string $extra = '') : string
{
    $salt = env('project.unique_identification', 'likeadmin');
    $encryptSalt = md5( $salt . uniqid());
    return md5($salt . $extra . time() . $encryptSalt);
}


/**
 * @notes 截取某字符字符串
 * @param $str
 * @param string $symbol
 * @return string
 * @author 段誉
 * @date 2021/12/28 18:24
 */
function substr_symbol_behind($str, $symbol = '.') : string
{
    $result = strripos($str, $symbol);
    if ($result === false) {
        return $str;
    }
    return substr($str, $result + 1);
}


/**
 * @notes 对比php版本
 * @param string $version
 * @return bool
 * @author 段誉
 * @date 2021/12/28 18:27
 */
function compare_php(string $version) : bool
{
    return version_compare(PHP_VERSION, $version) >= 0 ? true : false;
}


/**
 * @notes 检查文件是否可写
 * @param string $dir
 * @return bool
 * @author 段誉
 * @date 2021/12/28 18:27
 */
function check_dir_write(string $dir = '') : bool
{
    $route = root_path() . '/' . $dir;
    return is_writable($route);
}


/**
 * 多级线性结构排序
 * 转换前：
 * [{"id":1,"pid":0,"name":"a"},{"id":2,"pid":0,"name":"b"},{"id":3,"pid":1,"name":"c"},
 * {"id":4,"pid":2,"name":"d"},{"id":5,"pid":4,"name":"e"},{"id":6,"pid":5,"name":"f"},
 * {"id":7,"pid":3,"name":"g"}]
 * 转换后：
 * [{"id":1,"pid":0,"name":"a","level":1},{"id":3,"pid":1,"name":"c","level":2},{"id":7,"pid":3,"name":"g","level":3},
 * {"id":2,"pid":0,"name":"b","level":1},{"id":4,"pid":2,"name":"d","level":2},{"id":5,"pid":4,"name":"e","level":3},
 * {"id":6,"pid":5,"name":"f","level":4}]
 * @param array $data 线性结构数组
 * @param string $symbol 名称前面加符号
 * @param string $name 名称
 * @param string $id_name 数组id名
 * @param string $parent_id_name 数组祖先id名
 * @param int $level 此值请勿给参数
 * @param int $parent_id 此值请勿给参数
 * @return array
 */
function linear_to_tree($data, $sub_key_name = 'sub', $id_name = 'id', $parent_id_name = 'pid', $parent_id = 0)
{
    $tree = [];
    foreach ($data as $row) {
        if ($row[$parent_id_name] == $parent_id) {
            $temp = $row;
            $child = linear_to_tree($data, $sub_key_name, $id_name, $parent_id_name, $row[$id_name]);
            if ($child) {
                $temp[$sub_key_name] = $child;
            }
            $tree[] = $temp;
        }
    }
    return $tree;
}


/**
 * @notes 删除目标目录
 * @param $path
 * @param $delDir
 * @return bool|void
 * @author 段誉
 * @date 2022/4/8 16:30
 */
function del_target_dir($path, $delDir)
{
    //没找到，不处理
    if (!file_exists($path)) {
        return false;
    }

    //打开目录句柄
    $handle = opendir($path);
    if ($handle) {
        while (false !== ($item = readdir($handle))) {
            if ($item != "." && $item != "..") {
                if (is_dir("$path/$item")) {
                    del_target_dir("$path/$item", $delDir);
                } else {
                    unlink("$path/$item");
                }
            }
        }
        closedir($handle);
        if ($delDir) {
            return rmdir($path);
        }
    } else {
        if (file_exists($path)) {
            return unlink($path);
        }
        return false;
    }
}


/**
 * @notes 下载文件
 * @param $url
 * @param $saveDir
 * @param $fileName
 * @return string
 * @author 段誉
 * @date 2022/9/16 9:53
 */
function download_file($url, $saveDir, $fileName)
{
    if (!file_exists($saveDir)) {
        mkdir($saveDir, 0775, true);
    }
    $fileSrc = $saveDir . $fileName;
    file_exists($fileSrc) && unlink($fileSrc);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $file = curl_exec($ch);
    curl_close($ch);
    $resource = fopen($fileSrc, 'a');
    fwrite($resource, $file);
    fclose($resource);
    if (filesize($fileSrc) == 0) {
        unlink($fileSrc);
        return '';
    }
    return $fileSrc;
}


/**
 * @notes 去除内容图片域名
 * @param $content
 * @return array|string|string[]
 * @author 段誉
 * @date 2022/9/26 10:43
 */
function clear_file_domain($content)
{
    $fileUrl = FileService::getFileUrl();
    return str_replace($fileUrl, '/', $content);
}


/**
 * @notes 设置内容图片域名
 * @param $content
 * @return array|string|string[]|null
 * @author 段誉
 * @date 2022/9/26 10:43
 */
function get_file_domain($content)
{
    $preg = '/(<img .*?src=")[^https|^http](.*?)(".*?>)/is';
    $fileUrl = FileService::getFileUrl();
    return preg_replace($preg, "\${1}$fileUrl\${2}\${3}", $content);
}


/**
 * @notes uri小写
 * @param $data
 * @return array|string[]
 * @author 段誉
 * @date 2022/7/19 14:50
 */
function lower_uri($data)
{
    if (!is_array($data)) {
        $data = [$data];
    }
    return array_map(function ($item) {
        return strtolower(Str::camel($item));
    }, $data);
}


/**
 * @notes 获取无前缀数据表名
 * @param $tableName
 * @return mixed|string
 * @author 段誉
 * @date 2022/12/12 15:23
 */
function get_no_prefix_table_name($tableName)
{
    $tablePrefix = config('database.connections.mysql.prefix');
    $prefixIndex = strpos($tableName, $tablePrefix);
    if ($prefixIndex !== 0 || $prefixIndex === false) {
        return $tableName;
    }
    $tableName = substr_replace($tableName, '', 0, strlen($tablePrefix));
    return trim($tableName);
}


/**
 * @notes 生成编码
 * @param $table
 * @param $field
 * @param string $prefix
 * @param int $randSuffixLength
 * @param array $pool
 * @return string
 * @author 段誉
 * @date 2023/2/23 11:35
 */
function generate_sn($table, $field, $prefix = '', $randSuffixLength = 4, $pool = []) : string
{
    $suffix = '';
    for ($i = 0; $i < $randSuffixLength; $i++) {
        if (empty($pool)) {
            $suffix .= rand(0, 9);
        } else {
            $suffix .= $pool[array_rand($pool)];
        }
    }
    $sn = $prefix . date('YmdHis') . $suffix;
    if (app()->make($table)->where($field, $sn)->find()) {
        return generate_sn($table, $field, $prefix, $randSuffixLength, $pool);
    }
    return $sn;
}


/**
 * @notes 格式化金额
 * @param $float
 * @return int|mixed|string
 * @author 段誉
 * @date 2023/2/24 11:20
 */
function format_amount($float)
{
    if ($float == intval($float)) {
        return intval($float);
    } elseif ($float == sprintf('%.1f', $float)) {
        return sprintf('%.1f', $float);
    }
    return $float;
}

//生成suffix
function getSuffix($id){
    return "_".$id%8;
}

// 分库分表
function getTableSuffix($id) {

    return '_' . $id % 50;
}

function foramtContent($content) {

    $result = '';
    $lines = explode("\n", $content);
    foreach ($lines as $line) {
        $result .= "<p>$line</p>";  // 使用循环将每一行文本用 <p> 标签包裹起来
    }
    return $result;
}

function truncateAfterLastClosingPTag($str) {
    $lastClosingPTagPos = strrpos($str, '</p>');
    if ($lastClosingPTagPos !== false) {
        return substr($str, 0, $lastClosingPTagPos + 4); // 4 是因为 '</p>' 的长度是4
    } else {
        return $str;
    }
}

//生成suffix
function getChannelId($userInfo){
    $channel_id = $userInfo['sex']??2;
    if ($channel_id==0){
        $channel_id =2;
    }
    return $channel_id;
}

function generateNumericOrderNumber() {
    $time = time();  // 当前时间戳
    $microtime = microtime(); // 当前微秒数
    list($usec, $sec) = explode(" ", $microtime);
    $random = mt_rand(1000, 9999);  // 生成一个随机数

    $orderNumber = $sec . $usec . $random;  // 组合订单号
    // 移除连接符号，只保留数字部分
    $orderNumber = preg_replace('/\D/', '', $orderNumber);
    return $orderNumber;
}
/*获取快应用端传来的快应用ID
 * */
function getPlatform() {
    $headers = getallheaders();
    if (isset($headers['Platform'])) {
        return $headers['Platform'];
    } else {
        return 1; // 如果没传就返回1
    }
}

function msectime()
{
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}
//格式化数字
function formatDecimal($number) {
    $formatted_number = number_format((float)$number, 2);
    $formatted_number = rtrim($formatted_number, '0');
    $formatted_number = rtrim($formatted_number, '.');

    return $formatted_number;
}
/**
 * 计算概率
 *
 * @param $f
 * @param $s
 */
function getRate($f = 0, $s = 0)
{
    return ($f == 0 || $s == 0) ? '-' : bcmul(bcdiv($f, $s, 4), 100, 2) . '%';
}


/**
 * 计算除数
 *
 * @param int $f
 * @param int $s
 * @return int|string|null
 */
function getDiv($f = 0, $s = 0)
{
    return $s == 0 ? 0 : bcdiv($f, $s, 2);
}

/**
 * 计算数组和
 *
 * @param $data
 * @param $field
 * @return float
 */
function getSum($data, $field)
{
    return round(array_sum(array_column($data, $field)), 2);
}

function curlPost($url, $data) {
    $jsonData = json_encode($data);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($jsonData)
    ));
    $response = curl_exec($curl);
    if ($response === false) {
        $error = curl_error($curl);
    }
    curl_close($curl);
    return $response;
}

function bw_strsize($str,$lang=1)
{
    $str = strip_tags($str);
    $str = str_replace(array(" ","　","\n","\r","\t",PHP_EOL),"",$str);
    $str = preg_replace('/\\s/', '', $str);
    $str = preg_replace('/[\x80-\xff]{1,3}/', ' ', $str,-1,$n);//匹配中文或中文下的符号
    //$str = preg_replace('/[-\_\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",\'<>~\·`\?:;|]/', ' ', $str,-1,$j);//匹配英文下的符号
    //$n+=$j;
    $n += str_word_count($str);
    if(preg_match('/\d+/',$str)){
        preg_replace('/\d+/', ' ', $str,-1,$i);
        $n+=$i;
    }
    return $n;
}

function removeChromePrefix($userAgentString) {
    $pattern = '/Chrome\/\d+\.\d+\.\d+\.\d+/'; // 匹配 Chrome 版本号的正则表达式
    preg_match($pattern, $userAgentString, $matches); // 使用正则表达式匹配字符串中的 Chrome 版本号
    if (!empty($matches)) {
        $chromeVersion = $matches[0]; // 获取匹配到的 Chrome 版本号
        $position = strpos($userAgentString, $chromeVersion); // 获取 Chrome 版本号在原字符串中的位置
        if ($position !== false) {
            $trimmedString = substr($userAgentString, 0, $position); // 截取 Chrome 版本号之前的部分
            return $trimmedString;
        }
    }
    return $userAgentString; // 如果未匹配到 Chrome 版本号，则返回原始字符串
}

function convertUrlQuery($query)
{
    $queryParts = explode('&', $query);
    $params = array();
    foreach ($queryParts as $param) {
        $item = explode('=', $param);
        $params[$item[0]] = $item[1];
    }
    return $params;

}


function getPkgName($pkgPath)
{
    // hap://app/com.mw.reader/pages/index
    // 使用正则表达式匹配并提取出目标字符串
    $pattern = '/com\.[\w\d]+\.[\w\d]+/';
    preg_match($pattern, $pkgPath, $matches);

    return $matches[0] ?? '';
}
//根据图片地址判断图片是否存在
function imageExists($url) {
    $headers = get_headers($url);
    return stripos($headers[0], "200 OK") ? true : false;
}

function getUserCityByIP($ip) {
    // 调用IP-API的API接口
    $apiUrl = "http://ip-api.com/json/{$ip}?lang=zh-CN";
    $response = file_get_contents($apiUrl);

    // 解析API返回的JSON数据
    $data = json_decode($response, true);

    // 返回城市信息
    if ($data && $data['status'] == 'success') {
        return $data['city'];
    } else {
        return false;
    }
}

function getArrayByString(string $string) : array
{
    $delimiters = [',', '，'];
    $nameList   = str_replace(
        ['&nbsp;', "\r", '<br>', '<br/>'],
        [' ', "\n", "\n", "\n"],
        $string
    );
    $nameList = explode(
        $delimiters[0],
        str_replace($delimiters, $delimiters[0], $nameList)
    );
    $nameList = collect($nameList)->map(function ($name) {
        return trim($name);
    })->filter(function ($name) {
        return !empty($name);
    });

    return $nameList->all();
}

